<?php 
/**
 * Controller description
 * @since   13 мая 2010
 * @author diotheos
 */

class AjaxController extends Zend_Controller_Action
{

    public function init()
    {
        $this->_helper->layout->disableLayout();
        /* Initialize action controller here */
        $response = $this->getResponse();
        $response->setHeader('Content-Type', 'text/x-json');
    }

    /**
     * Список тэгов для скрипта-поиска.
     * @return void
     */
    public function searchAction()
    {

        $tag = $this->_request->getParam('tag');

        $tagsManager = new \Managers\Tags();

        $tags = $tagsManager->search($tag);

        $this->view->data = $tags;
        
        $this->renderScript('ajax/json.phtml');

    }

    public function showmailspamerAction()
    {
        $spamerManager = new Managers\Users();
        $this->view->mail_spamer_list = $spamerManager->MailSpamList();
    }

    public function showipspamerAction()
    {
        $spamerManager = new Managers\Users();
        $this->view->ip_spamer_list = $spamerManager->IPSpamList();
    }

    public function addspamerAction()
    {
        $radio = $this->_getParam('radio');
        $first_mail=$this->_getParam('mail');
        $mail = strtolower(trim($first_mail));
        $first_ip=$this->_getParam('ip');
        $ip = ip2long(trim($first_ip));

        $spamerManager = new Managers\Users();
        if ($radio=="mail"):
            if (!preg_match("/^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/", $mail)) /*(!eregi('^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$', $mail))*/
            {
                echo "Поле E-mail содержит недопустимый формат";
                die;
            }
            $this->view->is_mail_spamer = $spamerManager->IsMailSpamer($mail);
            if ($this->view->is_mail_spamer!=false)
                $this->view->already_mail_is = "Спамер с e-mail \"".$first_mail."\" уже есть!";
            else
            {
                $this->view->new_mail_spamer = $spamerManager->AddMailSpamer($mail);
                $this->view->message_new_mail_spamer = "Добавлен спамер с e-mail \"".$first_mail."\"";
                $this->view->new_mail_spamer = $spamerManager->IsMailSpamer($mail);
            }
        endif;
        if ($radio=="ip"):
            if ($ip==0)
            {
                echo "Поле IP содержит недопустимый формат";
                die;
            }
            $this->view->is_ip_spamer = $spamerManager->IsIpSpamer($ip);
            if ($this->view->is_ip_spamer!=false)
                $this->view->already_ip_is = "Спамер с IP \"".$first_ip."\" уже есть!";
            else
            {
                $this->view->new_ip_spamer = $spamerManager->AddIPspamer($ip);
                $this->view->message_new_ip_spamer = "Добавлен спамер с IP \"".$first_ip."\"";
                $this->view->new_ip_spamer = $spamerManager->IsIpSpamer($ip);
            }
        endif;

    }

    public function searchspamerAction()
    {
        $this->view->radio = $this->_getParam('radio');
        $first_mail=$this->_getParam('mail');
        $mail = strtolower(trim($first_mail));
        $first_ip=$this->_getParam('ip');
        $ip = ip2long(trim($first_ip));

        $spamerManager = new Managers\Users();
        if ($this->view->radio=="mail"):
            if (!preg_match("/^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/", $mail))
            {
                echo "Поле E-mail содержит недопустимый формат";
                die;
            }
            $this->view->is_spamer = $spamerManager->IsMailSpamer($mail);
            if ($this->view->is_spamer==false)
                $this->view->isnt = "Спамера с e-mail \"".$first_mail."\" нет!";
        endif;
        if ($this->view->radio=="ip"):
            if ($ip==0)
            {
                echo "Поле IP содержит недопустимый формат";
                die;
            }
            $this->view->is_spamer = $spamerManager->IsIpSpamer($ip);
            if ($this->view->is_spamer==false)
                $this->view->isnt = "Спамера с IP \"".$first_ip."\" нет!";
        endif;
    }

    public function updatedescAction()
    {

        $elm1 = $this->_getParam('elm1');
        $id = $this->_getParam('id');
    
        $tovar_manager = new Managers\Tovar();
        $this->view->tovar_update = $tovar_manager->UpdateDescriptionById($id, $elm1);
        $this->view->tovar = $tovar_manager->getDescriptionByTovarId($id);


    }

    public function addsubscriberAction()
    {
        $first_mail=$this->_getParam('mail');
        $mail = strtolower(trim($first_mail));

        if (!preg_match("/^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/", $mail))
            {
                echo "Поле E-mail содержит недопустимый формат";
                die;
            }
        $subscribeManager = new Managers\Mail();
        $isSubscribe = $subscribeManager->isSubscriber($mail);
        if ($isSubscribe!=false)
            die("E-mail \"'$first_mail'\" уже подписан на обновления");
        $newSubscriber = $subscribeManager->addSubscriber($mail);
        echo "Добавлен подписчик с e-mail \"'$first_mail'\"";

        $text = "Thank you!<br>
                 You have been subscribed successfully.<br>
                 <br>
                 For see last blocks go to : <a>BusinessScope blocks.</a><br>
                 For see last prices go to : <a>BusinessScope price lists.</a><br>
                 <br>
                 BusinessScope it is a several ways for promoting your business online : NewsScope, PricesScope, AdsScope.<br>
                 <br>
                 BusinessScope Team.<br>
                 Internet for Businesses & Customers (i4bc) Initiative.";
        $subject = "Welcome to BusinessScope!";
        $who_mail = "example@mail.com";
        $who_name ="Site";
        $whom_mail = $mail;
        $whom_name = "NEW subscriber";

        $sendMail = new Managers\Mail();
        //$sendMail->sendMail($text, $subject, $who_mail, $who_name, $whom_mail, $whom_name);
    }
    public function  starteditAction(){


    }
    public  function firstinAction(){
        $usersesion = new \Zend_Session_Namespace("usersession");
        $db=new \Managers\Users();
        $db->firstin($usersesion->user_id);


    }

    public function addsearctomailAction()
    {
        $user = $this->_getParam('user');
        $tags = $this->_getParam('tags');

        $TagsManager = new Managers\Mail();
        $usersesion = new \Zend_Session_Namespace("usersession");
        $userTagsBigArray = $TagsManager->allSearchMailList($usersesion->user_id);
            if (!empty($userTagsBigArray))
                $time = $userTagsBigArray[0][0]['time'];
            else
                $time=1;
        
        for ( $i=0; $i<count($tags); $i++ ):

        $isTags = $TagsManager->getSearchToMail($user, $tags[$i]);
        if ($isTags!=false)
            echo $this->view->translate("Вы уже подписались на обновления с тегом").$tags[$i]."<br>";
        else
        {
            $TagsManager->addSearchToMail($user, $tags[$i], $time);
            echo $this->view->translate("Поздравляем! Вы подписались на обновления с тегом").$tags[$i]."<br>";
        }
        endfor;
    }

    public function upupAction()
    {
        $user = $this->_getParam('user');
        $tags = $this->_getParam('tags');
        $time = $this->_getParam('time');

        $TagsManager = new Managers\Mail();
        $usersesion = new \Zend_Session_Namespace("usersession");
        for ($i=0; $i<count($tags); $i++):
            $tag = $tags[$i];
            $isTags = $TagsManager->getSearchToMail($user, $tag);
            $TagsManager->deleteSearchTag($isTags['id']);
        endfor;
            $TagsManager->upMailTime($usersesion->user_id, $time);
            $this->view->SearchTovars = $TagsManager->allSearchMailList($usersesion->user_id);
    }

    public function exmailAction()
    {
        $user = $this->_getParam('user');
        $old_mail = strtolower(trim($this->_getParam('oldmail')));
        $new_mail = strtolower(trim($this->_getParam('newmail')));

        if ( (!preg_match("/^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/", $old_mail)) || (!preg_match("/^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/", $new_mail)) )
            {
                echo $this->view->translate("Одно из полей E-mail содержит недопустимый формат");
                die;
            }

        $usersesion = new \Zend_Session_Namespace("usersession");
        $mailManager = new Managers\Mail();
        $rightMail = $mailManager->IsMail($usersesion->user_id, $old_mail);
        if ($rightMail==false)
        {
            echo $this->view->translate("Вы ввели не правильный E-mail");
            die;
        }

        $isMail = $mailManager->IsMail($usersesion->user_id, $new_mail);
        if ($isMail!=false)
        {
            echo $this->view->translate("Такой E-mail уже закреплён за другим пользователем");
            die;
        }

        $set_mail = $mailManager->ExchangeMail($usersesion->user_id, $new_mail);
        if ($set_mail)
            die('Все ок');
    }
}